<template>
	<div class="uiwu-upadte-model">
		<el-upload v-model:file-list="fileList" name="image" :action="`${baseURL}/upload/file`"
			list-type="picture-card" :limit="limit" :disabled="disabled" :on-preview="handlePictureCardPreview"
			:on-remove="handleRemove" :on-success="handleAvatarSuccess"
			:class="fileList.length >= limit ? 'el-upload-active' : ''">
			<el-icon>
				<Plus />
			</el-icon>
		</el-upload>
		<el-dialog v-model="dialogVisible">
			<img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;margin-top: 20px;" />
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	/**
	 * 图片上传组件 单张图片上传 limit 要设置为1 v-model绑定的类型是string 否则v-model绑定的是数组
	 * @author: 大佬
	 * @date: 2023-03-24 14:53:42
	 * @property {Numnber} limit 图片上传限制 默认9张 
	 * @property {Boolean} disabled 是否禁用 默认false
	 * @event {Function} update:modelValue 图片上传成功后触发
	 */
	import { onMounted, ref, watch } from 'vue';
	import { Plus } from '@element-plus/icons-vue';
	import type { UploadProps, UploadUserFile } from 'element-plus';
	import config from '@/config/config'; // 引入配置文件
	const baseURL = config.baseURL
	const props = defineProps({
		modelValue: {
			type: [String, Array],
			default: ''
		},
		limit: {
			default: 9,
			type: Number
		},
		disabled: {
			default: false,
			type: Boolean
		}
	})
	watch(() => props.modelValue, (newdata) => {
		if (props.limit == 1) {
			fileList.value = newdata ? [{ url: newdata }] : []
		} else {
			fileList.value = newdata ? newdata.map(item => ({ url: item })) : []
		}
	})
	const emit = defineEmits(['update:modelValue'])
	const fileList = ref<UploadUserFile[]>([])
	const dialogImageUrl = ref('')
	const dialogVisible = ref(false)
	/**
	 * 删除图片
	 */
	const handleRemove : UploadProps['onRemove'] = () => {
		const getImageUrl = fileList.value.map((item : any) => {
			return item.response?.filePath || item.url
		})
		if (props.limit === 1) {
			emit('update:modelValue', String(getImageUrl))
		} else {
			emit('update:modelValue', getImageUrl)
		}
	}
	/**
	 * 上传成功
	 */
	const handleAvatarSuccess : UploadProps['onSuccess'] = () => {
		const getImageUrl = fileList.value.map((item : any) => {
			return item.response?.filePath || item.url
		})
		if (props.limit === 1) {
			emit('update:modelValue', String(getImageUrl))
		} else {
			emit('update:modelValue', getImageUrl)
		}
	}
	const handlePictureCardPreview : UploadProps['onPreview'] = (uploadFile) => {
		dialogImageUrl.value = uploadFile.url!
		dialogVisible.value = true
	}
	onMounted(() => {
		if (props.limit == 1) {
			fileList.value = props.modelValue ? [{ url: props.modelValue }] : []
		} else {
			fileList.value = props.modelValue ? props.modelValue.map(item => ({ url: item })) : []
		}
	})
</script>

<style scoped>
	.el-upload-active /deep/ .el-upload.el-upload--picture-card {
		display: none;
	}
</style>